package com.yc.cloud.admin.task;

import com.yc.cloud.admin.constants.SnapshotConstants;
import com.yc.cloud.admin.dto.response.SnapshotResultVO;
import com.yc.cloud.admin.service.CameraSnapshotExecutor;
import com.yc.cloud.admin.service.HwCameraService;
import com.yc.cloud.admin.service.SnapshotStrategyResolver;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 抓图调度定时任务
 *
 * @author kinggu
 * @since 2025-10-10
 */
@Component
@Slf4j
public class SnapshotScheduleTask {
    
    @Resource
    private SnapshotStrategyResolver snapshotStrategyResolver;
    
    @Resource
    private CameraSnapshotExecutor cameraSnapshotExecutor;
    
    @Resource
    private HwCameraService hwCameraService;
    
    /**
     * 抓图调度任务 - 每30秒执行一次
     * 
     * 执行逻辑：
     * 1. 通过 SIP 服务器获取所有在线的摄像头
     * 2. 判断哪些摄像头当前时间需要抓图
     * 3. 批量执行抓图
     * 4. 记录执行结果
     */
    @Scheduled(fixedDelay = SnapshotConstants.SCHEDULE_INTERVAL_SECONDS * 1000)
    public void executeSnapshotSchedule() {
        log.debug("定时任务：开始执行抓图调度");
        
        long startTime = System.currentTimeMillis();
        
        try {
            // 1. 获取所有在线的摄像头ID（通过SIP服务器）
            List<Long> onlineCameraIds = hwCameraService.getOnlineCameraIds();
            
            if (onlineCameraIds.isEmpty()) {
                log.debug("定时任务：没有在线的摄像头");
                return;
            }
            
            log.debug("定时任务：共有{}个在线摄像头", onlineCameraIds.size());
            
            // 2. 筛选需要抓图的摄像头
            List<Long> needSnapshotCameraIds = onlineCameraIds.stream()
                .filter(cameraId -> {
                    try {
                        return snapshotStrategyResolver.shouldSnapshotNow(cameraId);
                    } catch (Exception e) {
                        log.error("判断摄像头[{}]是否需要抓图时异常", cameraId, e);
                        return false;
                    }
                })
                .toList();
            
            if (needSnapshotCameraIds.isEmpty()) {
                log.debug("定时任务：当前时间没有需要抓图的摄像头");
                return;
            }
            
            log.info("定时任务：需要抓图的摄像头数量: {}", needSnapshotCameraIds.size());
            
            // 3. 批量执行抓图
            Map<Long, SnapshotResultVO> results = cameraSnapshotExecutor.executeBatchSnapshot(needSnapshotCameraIds);
            
            // 4. 统计结果
            long successCount = results.values().stream()
                .filter(r -> "SUCCESS".equals(r.getStatus()))
                .count();
            long failedCount = results.size() - successCount;
            
            long duration = System.currentTimeMillis() - startTime;
            
            log.info("定时任务：抓图调度完成，总数: {}, 成功: {}, 失败: {}, 耗时: {}ms",
                results.size(), successCount, failedCount, duration);
            
        } catch (Exception e) {
            log.error("定时任务：抓图调度执行异常", e);
        }
    }
}

